<?php

function getCodeMsg ($key)
{
	$params = array();
	
	$params[10000] = '打款成功';
	$params[10101] = '单笔金额超出支付上限';
	$params[10102] = '总金额超出支付上限';
	$params[10103] = '余额不足';
	$params[10201] = '请求参数不正确';
	$params[10301] = 'sign 签名不正确';
	$params[10302] = 'key 值不存在或未开通';
	$params[10303] = 'appid 错误';
	$params[10304] = 'out_trade_no 重复,此订单号的打款记录已经存在,请检查是否重复打款';
	$params[10401] = '请求异常';
	$params[10501] = '订单不存在';

	return $params[$key];
}

function getStateMsg ($key)
{
	$params = array();
    //成功 success,失败 fail,处理中 processing
    $params['success'] = '成功';
    $params['fail'] = '失败';
    $params['processing'] = '处理中';

	return $params[$key];
}

function sign($text, $key, $input_charset)
{
    $text = $text . $key;

    return md5(getContentBytes($text, $input_charset));
}

function getContentBytes($content, $charset)
{
    $encode = mb_detect_encoding($content, array("ASCII", "UTF-8", "GB2312", "GBK", "BIG5"));
    if ($encode != $charset) {
        $content = iconv($encode, $charset, $content);
    }

    return $content;
}

function createLinkString($params)
{
    ksort($params);

    return http_build_query($params);
}

function paraFilter($params)
{
    $data = array();
    foreach ($params as $k => $v) {
        if (!empty($v)) {
            $data[$k] = $v;
        }
    }

    return $data;
}

function simplePost($url, $params)
{
    // $url = 'http://server.com/path';
    // $data = array('key1' => 'value1', 'key2' => 'value2');
    
    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header' => "Content-Type: text/html; charset=utf-8\r\n",
            'method' => 'POST',
            'content' => http_build_query($params)
        )
    );

    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    if ($result === false) {
        return "";
    }

    return $result;
}

//微派企业打款-账户余额查询接口调用
function WPayQueryBalanceDPay($url, $key, $appid)
{
    $api_url = $url;
    $api_key = $key;//秘钥(key)

    $params = array();
    $params['version'] = '2.0';
    $params['appid'] = $appid;

    $pretxt = createLinkString(paraFilter($params));

    $sign = strtoupper(sign($pretxt, $api_key, "utf-8"));

    $params['sign'] = $sign;

    $resString = simplePost($api_url, $params);

    $data = array();

    if (!empty($resString)) {
        //{"code":10000,"balance":35.93,"message":""}
        $obj = json_decode($resString, true);

        $data['code'] = $obj['code'];
        $data['msg'] = getCodeMsg($obj['code']);
        $data['message'] = $obj['message'];

        if ($obj['code'] == 10000) {
            //echo "余额:" . $obj['balance'];
            //return "调用成功: code[".$obj['code']."]{".getCodeMsg($obj['code'])."} 余额[".$obj['balance']."]";
            $data['balance'] = $obj['balance'];
        }
        // else {
        //     //echo "调用失败:" . $obj['code'] . "," . $obj['message'];
        //     return "调用失败: code[".$obj['code']."]{".getCodeMsg($obj['code'])."} message[".$obj['message']."]";
        // }
    }

    return $data;
}

//微派企业打款-交易状态查询接口调用
function WPayQueryOrderStateDPay($url, $key, $appid, $trade)
{
    $api_url = $url;
    $api_key = $key;//秘钥(key)

    $params = array();
    $params['version'] = '2.0';
    $params['appid'] = $appid;
    $params['out_trade_no'] = $trade;


    $pretxt = createLinkString(paraFilter($params));

    $sign = strtoupper(sign($pretxt, $api_key, "utf-8"));

    $params['sign'] = $sign;

    $resString = simplePost($api_url, $params);

    $data = array();

    if (!empty($resString)) {
         //{"code":10000,"state":"success","message":""}
        $obj = json_decode($resString, true);

        $data['code'] = $obj['code'];
        $data['msg'] = getCodeMsg($obj['code']);
        $data['message'] = $obj['message'];

        if ($obj['code'] == 10000) {
            //echo "交易状态:" . $obj['state'];
            //return "调用成功: code[".$obj['code']."]{".getCodeMsg($obj['code'])."} 交易状态[".$obj['state']."]";
            $data['state'] = $obj['state'];
            $data['statemsg'] = getStateMsg($obj['state']);
            
        }
        // else {
        //    // echo "调用失败:" . $obj['code'] . "," . $obj['message'];
        //     return "调用失败: code[".$obj['code']."]{".getCodeMsg($obj['code'])."} message[".$obj['message']."]";
        // }
    }

    return $data;
}

//微派企业打款(代付到微信零钱账户)接口调用
function WPayWeixinDPay($url, $key, $appid, $trade, $amount, $name, $mobile, $notify)
{
    $api_url = $url;
    $api_key = $key;//秘钥(key)

    $params = array();
    $params['version'] = '2.0';
    $params['appid'] = $appid;
    $params['transfer_type'] = 'weixin';
    $params['out_trade_no'] = $trade;
    $params['amount'] = $amount; //打款金额(单位:元),必填

    $params['cardholder_name'] = $name;
    $params['cardholder_mobile'] = $mobile;//持卡人手机号,非必填
    $params['notify_cardholder'] = $notify; //到账短信通知{n,y},非必填


    $pretxt = createLinkString(paraFilter($params));

    $sign = strtoupper(sign($pretxt, $api_key, "utf-8"));

    $params['sign'] = $sign;

    $resString = simplePost($api_url, $params);

    $data = array();

    if (!empty($resString)) {
         //{"message":"打款调用成功","code":10000}
        $obj = json_decode($resString, true);

        $data['code'] = $obj['code'];
        $data['msg'] = getCodeMsg($obj['code']);
        $data['message'] = $obj['message'];

        if ($obj['code'] == 10000) {
            //echo "调用成功:" . $obj['message'];
            //echo "提现地址:" . $obj['withdraw_url'];//提现地址,需要在用户在微信浏览器中访问
            //return "调用成功: code[".$obj['code']."]{".getCodeMsg($obj['code'])."} message[".$obj['message']."] 提现地址[".$obj['withdraw_url']."]";
            $data['withdraw_url'] = $obj['withdraw_url']; //如果返回结果中含有 withdraw_url，且不为空，则需要收款人在微信浏览器中访问此地址(同时需要在地址上附带 cardholder_name 参数)
            $data['cardholder_name'] = $params['cardholder_name'];
        }
        // else {
        //     //echo "调用失败:" . $obj['code'] . "," . $obj['message'];
        //     return "调用失败: code[".$obj['code']."]{".getCodeMsg($obj['code'])."} message[".$obj['message']."]";
        // }
    }

    return $data;
}

//微派企业打款(代付到支付宝账户)接口调用
function WPayAlipayDPay($url, $key, $appid, $trade, $amount, $bankcard_no, $name, $mobile, $notify)
{
    $api_url = $url;
    $api_key = $key;//秘钥(key)

    $params = array();
    $params['version'] = '2.0';
    $params['appid'] = $appid;
    $params['transfer_type'] = 'alipay';
    $params['out_trade_no'] = $trade;
    $params['amount'] = $amount; //打款金额(单位:元),必填

    $params['bankcard_no'] = $bankcard_no; //支付宝账号
    $params['cardholder_name'] = $name;
    $params['cardholder_mobile'] = $mobile;//持卡人手机号,非必填
    $params['notify_cardholder'] = $notify; //到账短信通知{n,y},非必填


    $pretxt = createLinkString(paraFilter($params));

    $sign = strtoupper(sign($pretxt, $api_key, "utf-8"));

    $params['sign'] = $sign;

    $resString = simplePost($api_url, $params);

    $data = array();

    if (!empty($resString)) {
         //{"message":"打款调用成功","code":10000}
        $obj = json_decode($resString, true);

        $data['code'] = $obj['code'];
        $data['msg'] = getCodeMsg($obj['code']);
        $data['message'] = $obj['message'];

        // if ($obj['code'] == 10000) {
        //     //echo "调用成功:" . $obj['message'];
		// 	return "调用成功: code[".$obj['code']."]{".getCodeMsg($obj['code'])."} message[".$obj['message']."]";
        // }
        // else {
        //     //echo "调用失败:" . $obj['code'] . "," . $obj['message'];
        //     return "调用失败: code[".$obj['code']."]{".getCodeMsg($obj['code'])."} message[".$obj['message']."]";
        // }
    }

    return $data;
}

//微派企业打款(代付到银行卡)接口调用
function WPayBankcardDPay($url, $key, $appid, $trade, $amount, $bankcard_no, $bank_name, $bank_branch, $cardholder_name, $cardholder_mobile, $notify_cardholder)
{
    $api_url = $url;
    $api_key = $key;//秘钥(key)

    $params = array();
    $params['version'] = '2.0';
    $params['appid'] = $appid;
    $params['transfer_type'] = 'weixin';
    $params['out_trade_no'] = $trade;
    $params['amount'] = $amount; //打款金额(单位:元),必填

    $params['bankcard_no'] = $bankcard_no;
    $params['bank_name'] = $bank_name;  //银行名称，如建设银行, 农业银行
    $params['bank_branch'] = $bank_branch; //分行名称,暂可为空

    $params['cardholder_name'] = $cardholder_name;
    $params['cardholder_mobile'] = $cardholder_mobile;//持卡人手机号,非必填
    $params['notify_cardholder'] = $notify_cardholder; //到账短信通知{n,y},非必填


    $pretxt = createLinkString(paraFilter($params));

    $sign = strtoupper(sign($pretxt, $api_key, "utf-8"));

    $params['sign'] = $sign;

    $resString = simplePost($api_url, $params);

    $data = array();

    if (!empty($resString)) {
         //{"message":"打款调用成功","code":10000}
        $obj = json_decode($resString, true);

        $data['code'] = $obj['code'];
        $data['msg'] = getCodeMsg($obj['code']);
        $data['message'] = $obj['message'];

        // if ($obj['code'] == 10000) {
        //     //echo "调用成功:" . $obj['message'];
        //     return "调用成功: code[".$obj['code']."]{".getCodeMsg($obj['code'])."} message[".$obj['message']."]";
        // }
        // else {
        //     //echo "调用失败:" . $obj['code'] . "," . $obj['message'];
        //     return "调用失败: code[".$obj['code']."]{".getCodeMsg($obj['code'])."} message[".$obj['message']."]";
        // }
    }

    return $data;
}

?>